package com.tan.steamship.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.steamship.domain.OrdersPo;
import com.tan.steamship.mapper.OrdersMapper;
import com.tan.steamship.service.OrdersService;
import com.tan.steamship.service.ShoppingCartService;
import com.tan.steamship.vo.CartVo;
import com.tan.steamship.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 85726
* @description 针对表【orders(订单信息表)】的数据库操作Service实现
* @createDate 2025-03-12 14:50:02
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersPo>
    implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Override
    public List<List<OrderVo>> getOrderByUserId(Integer userId) {
        ArrayList<List<OrderVo>> ret = new ArrayList<>();
        List<OrderVo> orderByUserId = ordersMapper.getOrderByUserId(userId);
        if (CollUtil.isNotEmpty(orderByUserId)) {
            // 将同一个订单放在一组
            Map<String, List<OrderVo>> collect = orderByUserId.stream().collect(Collectors.groupingBy(OrderVo::getOrderId));
            Collection<List<OrderVo>> values = collect.values();
            ret.addAll(values);
        }
        return ret;
    }

    @Override
    public void addOrder(List<CartVo> cartVoList, Integer userId) {
        String orderId = IdWorker.getIdStr();
        List<OrdersPo> saveOrder = new ArrayList<>();
        List<Integer> shoppingCarId = new ArrayList<>();
        for (CartVo cartVo : cartVoList) {
            OrdersPo orderPo = new OrdersPo();
            orderPo.setOrderId(orderId);
            orderPo.setOrderStatus("已支付");
            orderPo.setBookingDate(new Date());
            orderPo.setPrice(cartVo.getPrice());
            orderPo.setRouteNum(cartVo.getNum());
            orderPo.setRouteId(cartVo.getRouteId());
            orderPo.setUserId(userId);
            saveOrder.add(orderPo);
            shoppingCarId.add(cartVo.getId());
        }
        this.saveBatch(saveOrder);
        shoppingCartService.removeByIds(shoppingCarId);
    }
}




